package com.xiaoma.pattern.observer.event;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class EventListener {
    private Map<String, Events> events = new HashMap<>();

    /**
     * 添加监听
     * @param eventType
     * @param target
     */
    public void addListener(String eventType,Object target){
        try {
            this.addListener(eventType,target,target.getClass().getMethod("on"+toUpperFirstCase(eventType),Events.class));
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }


    /**
     * 添加监听
     * @param eventType
     * @param target
     * @param callback
     */
    public void addListener(String eventType, Object target, Method callback){
        events.put(eventType,new Events(target,callback));
    }

    /**
     * 事件触发
     * @param event
     */
    public void trigger(Events event){
        event.setTime(System.currentTimeMillis());
        event.setSource(this);

        if (event.getCallback() != null){
            try {
                event.getCallback().invoke(event.getTarget(),event);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 事件名称触发
     * @param eventName
     */
    public void trigger(String eventName){
        if (events.containsKey(eventName)){
            trigger(events.get(eventName).setTrigger(eventName));
        }
    }

    /**
     * 逻辑处理的私有方法，首字母大写
     */
    private String toUpperFirstCase(String str){
        char[] chars = str.toCharArray();
        chars[0] -= 32;
        return String.valueOf(chars);
    }
}

